const router = require('koa-router')();
const scripts = require('./scripts/server');

router.prefix('/api/trac', '服务器监听相关接口');

router.get('/configs', async (ctx) => {
  let rs = await ctx.sqlite.queryForList(scripts.getConfigs);

  ctx.body = rs;
}, '获取所有配置信息');

router.post('/save', async (ctx) => {
  let info = ctx.request.body || {};

  if (!info.name) {
    ctx.body = ctx.getResponse('名称不能为空！');

    return;
  }

  let res = await ctx.sqlite.queryForObject(scripts.getConfig, { name: info.name });

  if (res.data) {
    info.id = res.data.Id;

    await ctx.sqlite.execute(scripts.updateConfig, info);
  } else {
    await ctx.sqlite.execute(scripts.addConfig, info);
  }

  ctx.body = ctx.getResponse();
}, {
  desc: '保存配置信息', body: {
    name: { type: 'string', desc: '名称' },
    value: { type: 'string', desc: '配置信息' },
    description: { type: 'string', desc: '描述' }
  }
});

router.delete('/:id', async (ctx) => {
  let rs = await ctx.sqlite.execute(scripts.removeConfig, { id: ctx.params.id });

  ctx.body = rs;
}, { desc: '删除配置信息', id: '配置编号' });

module.exports = router;